<template>
  <div>
    <a-modal :title="title" wrapClassName="addModal" :visible="visible" :destroyOnClose="true" @cancel="handleCancel()" :footer="null" width="860px">
      <div class="scroll">
        <a-form-model ref="ruleForm" layout="vertical" :model="form" :rules="rules">
          <div class="row">
            <a-form-model-item label="菜品类目" ref="menuId" prop="menuId">
              <a-select v-model="form.menuId" size="large" class="select" placeholder="请选择任务类型" :options="typeList">
              </a-select>
            </a-form-model-item>
          </div>
          <div class="row">
            <a-form-model-item label="菜品名称" ref="title" prop="title">
              <a-input size="large" v-model="form.title" class="input" placeholder="请输入菜品名称"></a-input>
            </a-form-model-item>
          </div>
          <div>
            <a-form-model-item label="菜品卖点" ref="sellPoint" prop="sellPoint">
              <a-textarea placeholder="请输入任务描述" v-model="form.sellPoint" size="large" />
            </a-form-model-item>
          </div>
          <div class="row">
            <a-form-model-item label="商品价格" ref="price" prop="price">
              <a-input-number
                size="large"
                v-model="form.price"
                class="input"
                placeholder="请输入商品价格"
                :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                :parser="value => value.replace(/\$\s?|(,*)/g, '')"
                :precision="2"
              />
            </a-form-model-item>
          </div>
          <div class="row">
            <a-form-model-item label="商品折扣价格" ref="disPrice" prop="disPrice">
              <a-input-number
                size="large"
                v-model="form.disPrice"
                class="input"
                placeholder="请输入商品折扣价格"
                :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                :parser="value => value.replace(/\$\s?|(,*)/g, '')"
                :precision="2"
              />
            </a-form-model-item>
          </div>
          <div class="row">
            <a-form-model-item label="上传图片" ref="img" prop="img">
              <a-upload
                name="uploadFile"
                list-type="picture-card"
                class="avatar-uploader"
                action="/api/pic/upload?dir=image"
                :show-upload-list="false"
                :before-upload="beforeUpload"
                :data="uploadParams"
                @change="handleChange"
              >
                <img v-if="form.img" :src="form.img" alt="avatar" style="width: 100%" />
                <div v-else>
                  <a-icon :type="loading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">上传图片</div>
                </div>
              </a-upload>
            </a-form-model-item>
          </div>
        </a-form-model>
      </div>
      <div class="submit-con">
        <a-button type="primary" icon="close-circle" ghost @click="handleCancel()" class="cancel">
          取消退出
        </a-button>
        <a-button type="primary" icon="check-circle" @click="save()" class="issue">
          保存
        </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { message } from "ant-design-vue";
import _ from "lodash";
import moment from "moment";
import api from "@/util/api";

export default {
  components: {},
  props: {
    title: {
      type: String,
      default: "新建任务"
    },
    clearDetail: {
      type: Function
    },
    detail: {
      type: Object
    },
    refresh: {
      type: Function
    }
  },
  data() {
    return {
      typeList: [],
      uploadParams: {},
      visible: false,
      rules: {
        menuId: [
          { required: true, message: "请选择菜品类目", trigger: "change" }
        ],
        title: [{ required: true, message: "请输入菜品名称", trigger: "blur" }],
        sellPoint: [
          { required: true, message: "请输入商品卖点", trigger: "blur" }
        ],
        price: [
          { required: true, message: "请输入商品价格", trigger: "change" }
        ],
        disPrice: [
          { required: true, message: "请输入商品折扣价格", trigger: "change" }
        ],
        img: [
          { required: false, message: "请上传图片", trigger: "change" }
        ]
      },
      headers: null,
      form: {
        menuId: undefined,
        title: null,
        sellPoint: null,
        price: 0.00,
        disPrice: 0.00,
        img: null
      },
      loading: false
    };
  },
  watch: {
    detail: {
      handler(val) {
        if (val) {
          for (const key in val) {
            if (Object.prototype.hasOwnProperty.call(val, key)) {
              const element = val[key];
              this.$set(this.form, key, element)
              
            }
          }
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.fetchMenuOptions();
  },
  methods: {
    fetchMenuOptions() {
      api.get(`/api/menu/list`, { params: { id: 1 } }).then(res => {
        if (res && Array.isArray(res)) {
          this.typeList = res.map(item => ({
            title: item.text,
            value: item.id
          }));
        } else {
          console.error('数据格式不正确', res.data);
        }
      }).catch(error => {
        console.error('获取菜单选项失败', error);
      });
    },
    save() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const params = _.cloneDeep(this.form);
          if (this.title === "新增菜品") {
            this.add(params);
          } else {
            this.edit(params);
          }
        } else {
          return false;
        }
      });
    },
    add(params) {
      const formData = new FormData();
      for (const key in params) {
        if (Object.hasOwnProperty.call(params, key) && key !== 'img') {
          formData.append(key, params[key]);
        }
      }
      if (params.img) {
        formData.append('img', params.img);
      }
      api.post('/api/disk/save', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(() => {
        this.visible = false;
        this.refresh();
        message.success("添加成功");
        this.resetForm();
      }).catch(() => {
        message.error("添加失败");
      });
    },
    edit(params) {
      const formData = new FormData();
      for (const key in params) {
        if (Object.hasOwnProperty.call(params, key) && key !== 'img') {
          formData.append(key, params[key]);
        }
      }
      if (params.img) {
        formData.append('img', params.img);
      }
      api.put(`/api/disk/update`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(() => {
        this.visible = false;
        this.refresh();
        message.success("修改成功");
        this.resetForm();
      }).catch(() => {
        message.error("修改失败");
      });
    },
    resetForm() {
      this.form = {
        menuId: undefined,
        title: null,
        sellPoint: null,
        price: 0.00,
        disPrice: 0.00,
        img: null
      };
      this.clearDetail();
    },
    handleCancel() {
      this.visible = false;
      this.resetForm();
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        message.error('请选择图片!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片最大2MB!');
      }
      return isJpgOrPng && isLt2M;
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true;
        return;
      }
      if (info.file.status === 'done') {
        this.loading = false;
        this.form.img = info.file.response.url;
      }
      if (info.file.status === 'error') {
        this.loading = false;
        message.error('上传失败');
      }
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep {
  .addModal {
    .ant-modal-body {
      padding: 8px 0 64px 0;
    }

    .scroll {
      padding: 0 80px;
      height: 530px;
      overflow-y: scroll;
    }

    .row {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }

    .input {
      width: 320px;
    }

    .is-center {
      padding: 0px !important;
      height: 31px !important;
      background: #fafafa;
      color: #434343;
    }

    .submit-con {
      text-align: center;

      .cancel {
        margin-right: 24px;
      }

      .cancel,
      .issue {
        width: 148px;
        height: 40px;
      }
    }

    .select {
      width: 320px;
    }

    .avatar-uploader > .ant-upload {
      width: 128px;
      height: 128px;
    }

    .ant-upload-select-picture-card i {
      font-size: 32px;
      color: #999;
    }

    .ant-upload-select-picture-card .ant-upload-text {
      margin-top: 8px;
      color: #666;
    }
  }
}
</style>